<?php
class ControllerCommonRegister extends Controller {
	private $error = array();

	public function index() {

		if ($this->user->isLogged()) {
			$this->response->redirect($this->url->link('catalog/product', 'token=' . $this->session->data['token'], true));
		}

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
			$this->user->register($this->request->post['mobile'], html_entity_decode($this->request->post['password'], ENT_QUOTES, 'UTF-8'));
			$this->session->data['token'] = token(32);
			$this->response->redirect($this->url->link('catalog/product', 'token=' . $this->session->data['token'], true));
		}

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		$data['action'] = $this->url->link('common/register', '', true);
		$data['login'] = $this->url->link('common/login', '', true);

		if (isset($this->request->post['mobile'])) {
			$data['mobile'] = $this->request->post['mobile'];
		} else {
			$data['mobile'] = '';
		}

		if (isset($this->request->post['password'])) {
			$data['password'] = $this->request->post['password'];
		} else {
			$data['password'] = '';
		}

		$data['header'] = $this->load->controller('common/header');
		$data['footer'] = $this->load->controller('common/footer');

		$this->response->setOutput($this->load->view('common/register', $data));
	}

	protected function validate() {

		if (!$this->error && empty($this->request->post['mobile'])) {
			$this->error['warning'] = '手机号码不能为空!';
		}

		if (!$this->error && empty($this->request->post['password'])) {
			$this->error['warning'] = '密码不能为空!';
		}

		if(!$this->error && !preg_match('/^1[34578]\d{9}$/', $this->request->post['mobile'])){
			$this->error['warning'] = '手机号码格式错误!';
		}

		if(!$this->error && !preg_match('/^1[34578]\d{9}$/', $this->request->post['mobile'])){
			$this->error['warning'] = '手机号码格式错误!';
		}

		if(!$this->error && $this->user->existByMobile($this->request->post['mobile'])){
			$this->error['warning'] = '手机号码已存在!';
		}

		return !$this->error;
	}
}
